package com.mymail.test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public abstract class DAOImp {
	private static Connection con;
	private static PreparedStatement stmt = null;
	private static ResultSet result = null;

	private boolean execute(String sql, Object[] objs) throws SQLException {
		con = SQLTest.getConnect();
		stmt = con.prepareStatement(sql);
		if (objs != null) {
			for (int i = 0; i < objs.length; ++i) {
				stmt.setObject(i + 1, objs[i]);
			}
		}
		if (stmt.execute()) {
			result = stmt.getResultSet();
			return true;
		} else {
			return false;
		}
	}

	protected boolean exe(String sql, Object[] objs) {
		try {
			execute(sql, objs);
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		} finally {
			close();
		}
	}

	protected boolean findOne(String sql, Object[] objs, Object obj) {
		try {
			if (execute(sql, objs)) {
				setAtribute(result, obj);
				return true;
			} else {
				return false;
			}
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		} finally {
			close();
		}
	}

	@SuppressWarnings("unchecked")
	protected ArrayList findArray(String sql, Object[] objs) {
		con = SQLTest.getConnect();
		ArrayList arr = new ArrayList();
		try {
			if (execute(sql, objs)) {
				while (result.next())
					arr.add(getEntity(result));
			}
			return arr;
		} catch (SQLException e) {
			e.printStackTrace();
			return arr;
		} finally {
			close();
		}
	}
	
	private void close(){
		try {
			if (result != null) {
				result.close();
			}
			if (stmt != null) {
				stmt.close();
			}
		} catch (SQLException e) {
		} finally {
			result = null;
			stmt = null;
			SQLTest.close();
		}
	}

	protected abstract Object getEntity(ResultSet result) throws SQLException;

	protected abstract void setAtribute(ResultSet result, Object obj)
			throws SQLException;

}
